import { createServer, Command, ModeOptions, LogLevelOptions, logger, addRoute } from "f2e-server3"
import { createMiddleRBAC, createServiceFile } from "f2e-middle-rbac"
import tailwindcss from "tailwindcss"
import { setDocDir } from "./config"
import { middle_upload } from "./actions"
import "./preview"
import path from "path"
import fs from "fs"

const pathConfigTitle = path.join(process.cwd(), './.f2e_cache/config.title');

if (!fs.existsSync(pathConfigTitle)) {
    fs.writeFileSync(pathConfigTitle, 'EasyDoc')
}

const command = new Command('easydocs')
    .option('-p, --port <port>', '端口号', 8999)
    .option('-d, --dir <dir>', '文档存储根路径', './.f2e_cache/docs')
    .option('-m, --mode <mode>', '构建模式', 'prod', ModeOptions)
    .option('-l, --level <level>', '日志级别', 'INFO', LogLevelOptions)
    .action(async (options) => {
        const { port, dir, mode, level } = options
        setDocDir(dir)
        const service = createServiceFile({})

        addRoute("/api/all_users", async () => {
            const res = await service.userService.userList({
                page: 1,
                pageSize: 9999,
            })
            return res.data?.list ?? []
        })

        logger.setLevel(level)
        createServer({
            port, mode,
            gzip: true,
            ssl: {
                passphrase: 'x509',
                key_file_name: path.join(__dirname, '../ssl/private.pem'),
                cert_file_name: path.join(__dirname, '../ssl/csr.crt'),
            },
            try_files: "index.html",
            buildFilter: (pathname) => {
                return /^(index|favicon|style|$)/.test(pathname)
            },
            watchFilter: (pathname) => {
                return /^(index|src|style|$)/.test(pathname)
            },
            postcss: {
                entryPoints: "src/index.css",
                plugins: [
                    require('postcss-import'),
                    tailwindcss,
                ],
            },
            middlewares: [
                createMiddleRBAC(service, { logout_url: '/logout' }),
                middle_upload,
            ],
            include: {
                entryPoints: ["index.html"],
            },
            auth: {
                store: service.userService,
                white_list: [
                    "^export/[0-9]+",
                ]
            },
        })
    })
command.parse(process.argv)